package com.alatus.web;

import com.alatus.constant.Constants;
import com.alatus.model.TCustomer;
import com.alatus.query.CustomerQuery;
import com.alatus.result.CustomerExcel;
import com.alatus.result.Result;
import com.alatus.service.CustomerService;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @PostMapping(value = "/api/clue/customer")
    public Result transferCustomer(@RequestBody CustomerQuery customerQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        customerQuery.setToken(token);
        Boolean convert = customerService.convertCustomer(customerQuery);
        return convert ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('customer:list')")
    @GetMapping(value = "/api/customers")
    public Result CustomersByPages(@RequestParam(value = Constants.CURRENT,required = false)Integer current){
        if(current == null){
            current = 1;
        }
        PageInfo<TCustomer> pageInfo = customerService.getCustomerByPage(current);
        return Result.OK(pageInfo);
    }

    @PreAuthorize(value = "hasAuthority('customer:export')")
    @GetMapping(value = "/api/exportExcel")
    public void exportExcel(@RequestParam(value = Constants.IDS,required = false)String ids, HttpServletResponse response) throws IOException {
        List<String> idList = null;
        if(!ObjectUtils.isEmpty(ids)){
            idList = Arrays.asList(ids.split(","));
        }
        //要想让浏览器弹出下载框，后端要设置一下响应头信息
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding(Constants.UTF_8);
        response.setHeader("X-Frame-Options", "allow-from uri");// 解决IFrame拒绝的问题
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(Constants.CUSTOMER_FILE_NAME,Constants.UTF_8)+System.currentTimeMillis() +".xlsx");
        List<CustomerExcel> dataList = customerService.getCustomerByExcel(idList);
        EasyExcel.write(response.getOutputStream(), CustomerExcel.class)
                .sheet()
                .doWrite(dataList);
    }
}
